using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Bom;

namespace WPF_MVVM_Test.Services.Bom
{
    /// <summary>
    /// 产品服务类
    /// </summary>
    public class ProductService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888"; // 根据你的API地址调整

        public ProductService()
        {
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Accept", "text/plain");
        }

        /// <summary>
        /// 获取产品分页列表
        /// </summary>
        /// <param name="queryParams">查询参数</param>
        /// <returns>产品分页数据</returns>
        public async Task<ProductApiResponses> GetProductListAsync(ProductQueryParams queryParams)
        {
            try
            {
                // 构建查询URL
                var url = $"{_baseUrl}/api/Productentity/GetProductList";
                var queryString = BuildQueryString(queryParams);
                if (!string.IsNullOrEmpty(queryString))
                {
                    url += "?" + queryString;
                }

                // 发送GET请求
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();

                    // 配置JSON序列化选项
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
                    };

                    var result = JsonSerializer.Deserialize<ProductApiResponses>(jsonContent, options);
                    return result ?? new ProductApiResponses();
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (HttpRequestException ex)
            {
                throw new Exception($"网络请求失败: {ex.Message}");
            }
            catch (JsonException ex)
            {
                throw new Exception($"JSON数据解析失败: {ex.Message}\n请检查API返回的数据格式是否正确");
            }
            catch (Exception ex)
            {
                throw new Exception($"获取产品列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 构建查询字符串
        /// </summary>
        /// <param name="queryParams">查询参数</param>
        /// <returns>查询字符串</returns>
        private string BuildQueryString(ProductQueryParams queryParams)
        {
            var queryParts = new List<string>();

            if (!string.IsNullOrEmpty(queryParams.MaterialNumber))
            {
                queryParts.Add($"MaterialNumber={Uri.EscapeDataString(queryParams.MaterialNumber)}");
            }

            if (!string.IsNullOrEmpty(queryParams.SpecificationModel))
            {
                queryParts.Add($"SpecificationModel={Uri.EscapeDataString(queryParams.SpecificationModel)}");
            }

            if (!string.IsNullOrEmpty(queryParams.Unit))
            {
                queryParts.Add($"Unit={Uri.EscapeDataString(queryParams.Unit)}");
            }

            queryParts.Add($"PageIndex={queryParams.PageIndex}");
            queryParts.Add($"PageSize={queryParams.PageSize}");

            return string.Join("&", queryParts);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}